package com.rengwuxian.materialedittext;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


/**
 * Created by Rich on 2017/7/14.
 * 一键清理EditText
 */

public class ClearEditText extends MaterialEditText implements View.OnFocusChangeListener, TextWatcher {

    private Drawable delete;// 一键删除的按钮
    private Drawable deleteClick;// 一键删除的按钮
    private Drawable deleteIcon;// 一键删除的显示图标
    private boolean hasFocus;// 控件是否有焦点
    private int iconType;
    private Context context;

    public ClearEditText(Context context) {
        super(context);
        init();
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText);
        if (typedArray != null) {
            iconType = typedArray.getInt(R.styleable.ClearEditText_type, 0);
            delete = typedArray.getDrawable(R.styleable.ClearEditText_icon_delete);
            deleteClick = typedArray.getDrawable(R.styleable.ClearEditText_icon_delete_click);
            typedArray.recycle();
        }
        init();
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText);
        if (typedArray != null) {
            iconType = typedArray.getInt(R.styleable.ClearEditText_type, 0);
            delete = typedArray.getDrawable(R.styleable.ClearEditText_icon_delete);
            deleteClick = typedArray.getDrawable(R.styleable.ClearEditText_icon_delete_click);
            typedArray.recycle();
        }
        init();
    }

    private void init() {
        initClearDrawable();
        // 设置焦点改变的监听
        setOnFocusChangeListener(this);
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(this);
    }


    /**
     * 还原图标默认图片
     */
    private void initClearDrawable() {
        delete.setBounds(0, 0, (int) getResources().getDimension(R.dimen.m_eye_width), (int) getResources().getDimension(R.dimen.m_eye_width));//设置Drawable的宽高和TextSize的大小一致
        deleteClick.setBounds(0, 0, (int) getResources().getDimension(R.dimen.m_eye_width), (int) getResources().getDimension(R.dimen.m_eye_width));//设置Drawable的宽高和TextSize的大小一致
        deleteIcon = delete;
    }

    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible
     */
    private void setClearIconVisible(boolean visible) {
        Drawable right = visible ? deleteIcon : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
        setCompoundDrawablePadding(30);
        //setPaddingRelative(20,10,10,10);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_DOWN:
                //获取屏幕上点击的坐标
                float x = event.getX();
                float y = event.getY();
                //如果坐标在我们的文字区域内，则将点击的文字改颜色
                // (x < (getWidth() - getPaddingRight())) &&
                if ((x > (getWidth() - getTotalPaddingRight())) && getText().length() > 0) {
                    deleteIcon = deleteClick;
                    //  deleteIcon.setBounds(0, 0, (int) getResources().getDimension(R.dimen.delete), (int) getResources().getDimension(R.dimen.delete));
                    setClearIconVisible(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                //点击抬起后，回复初始位置。
                deleteIcon = delete;
                setClearIconVisible(true);
        }

        if (deleteIcon != null && event.getAction() == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            // 判断触摸点是否在水平范围内
            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight()))
                    && (x < (getWidth() - getPaddingRight()));
            // 获取删除图标的边界，返回一个Rect对象
            //   Rect rect = deleteIcon.getBounds();
            //   // 获取删除图标的高度
            //  int height = rect.height();
            //   int y = (int) event.getY();
            // 计算图标底部到控件底部的距离
            //  int distance = (getHeight() - height) / 2;
            // 判断触摸点是否在竖直范围内(可能会有点误差)
            // 触摸点的纵坐标在distance到（distance+图标自身的高度）之内，则视为点中删除图标
            //    boolean isInnerHeight = (y > distance) && (y < (distance + height));
            if (isInnerWidth) {
                this.setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        this.hasFocus = hasFocus;
        if (hasFocus) {
            setSelection(getText().length());//将光标移至文字末尾
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (hasFocus) {
            setClearIconVisible(charSequence.length() > 0);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable.length() == 0) {
            setTypeface(Typeface.DEFAULT);
        } else {
            if (iconType != 10) {
                setTypeface(Typeface.DEFAULT_BOLD);
            }

        }
    }


}
